package com.projectplace.GUI;

/*
 * Copyright (c) 2011 Projectplace International AB
 * Permission is hereby granted, free of charge, to any person 
 * obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, 
 * publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, 
 * subject to the following conditions:The above copyright notice and this 
 * permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

import java.util.ArrayList;
import java.util.List;
import com.projectplace.R;
import com.projectplace.SingeltonPPClient;
import com.projectplace.GUI.Callback.CacheCallbackInterface.ReponseCompareConversations;
import com.projectplace.GUI.Callback.CacheCallbackInterface.ResponseProjectConversation;
import com.projectplace.GUI.Database.CacheHelper;
import com.projectplace.GUI.adapter.Conversation_ProjectConversation_Adapter;
import com.projectplace.api.ConversationsApi;
import com.projectplace.api.objectResponses.Conversation.Conversation;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;


public class ProjectConversation extends ListActivity {

	private static ArrayList<Conversation> projectConversation;
	private static Conversation_ProjectConversation_Adapter projectConversationAdapter;
	
	private final static String LOG_TAG ="ProjectConversation";
	private static ListActivity activity;
	
	public static final String PREFS = "conversationFile";
	private static SharedPreferences mSettings;
	private static Handler hand;
	private final String identifier="projectID";
	private static String idOfProject="";
	
	@Override
	public void onCreate(Bundle saveInstanceState){
		super.onCreate(saveInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		
		setContentView(R.layout.list);
		hand = new Handler();
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.my_title);
		
		
		activity = this;
		projectConversation =  new ArrayList<Conversation>();
		idOfProject = getIntent().getStringExtra(identifier);
		mSettings = getSharedPreferences(Conversations.PREFS, Context.MODE_PRIVATE);
		
		if(idOfProject != null){
			CacheHelper.getMyProjectConversation(activity, hand, idOfProject,
					new ResponseProjectConversation() {

						public void onFail(Error err) {
							// TODO Auto-generated method stub
							Log.d(LOG_TAG, err.getMessage());			
						}

						public void onReceive(List<Conversation> cachedProjectConversations) {
							if(cachedProjectConversations != null && !cachedProjectConversations.isEmpty()){
								if(!projectConversation.isEmpty())
									projectConversation.clear();
								projectConversation.addAll(cachedProjectConversations);
								projectConversationAdapter = new Conversation_ProjectConversation_Adapter(
										activity, projectConversation);
								activity.setListAdapter(projectConversationAdapter);
							}else{
								//Cache is empty and we need to clear the timestamp for that projectConversation
								saveTimeStampForProject(idOfProject, "");
							}
						}
					});
		}
		
	}
	
	public void onClick(View v){
		finish();
	}
	
	//Listens for user clicks, have to parse from long since that's what the adapter is returning
	public void onListItemClick(ListView l,View v,int position,long id){
		String idOfClickedProject = String.valueOf(id);
		Log.d(LOG_TAG +LOG_TAG +LOG_TAG, idOfClickedProject);
		Intent intent = new Intent().setClass(this, SingelConversation.class);
		intent.putExtra(identifier, idOfClickedProject);
		startActivity(intent);
	}
	
	
	/*
	 * Metod takes you one step ahead in the gui from listing myProjects to list
	 * projectconversation within that project
	 */
	
	public void onStart(){
		super.onStart();
		
		String lastKnownTime = mSettings.getString(idOfProject, "");
		
		Log.d(LOG_TAG +" TIME OF PROJECT CONVERSATION: ", lastKnownTime);
		
		ConversationsApi.getProjectConversations(SingeltonPPClient.getInstance(), hand, idOfProject, lastKnownTime, new com.projectplace.api.Callback.Callback.ResponseListenerProjectConversations() {
			
			public void SERVER_ERROR(Error err) {
				// TODO Auto-generated method stub
				
			}  
			
			public void BAD_TOKEN_ERROR(Error err) {
				// TODO Auto-generated method stub
				
			}
			
			public void onReceive(List<Conversation> projectConv) {
				// TODO Auto-generated method stub
				//if(!projectConversation.isEmpty())
					//CacheHelper.saveMyProjectConversations(activity, projectConversation,idOfClickedProject);
				 
				/*
				 *  This is freezing the UI thread when posting back
				 *  ------------------------------------------------
				 */
				if(!projectConversation.isEmpty() && projectConv != null){
					CacheHelper.CompareTwoListConversations(projectConv, projectConversation, hand, new ReponseCompareConversations() {
						
						public void onFail(Error err) {
							// TODO Auto-generated method stub
							Log.d(LOG_TAG +" CompareTwoListConversations", err.getMessage());
						}
	
						public void onReceive(
								List<Conversation> upToDateConversationList) {
							saveTimeStampForProject(idOfProject, upToDateConversationList.get(0).getLast_post_time());
							projectConversation.clear(); 
							projectConversation.addAll(0,upToDateConversationList);
							CacheHelper.saveMyProjectConversations(activity, projectConversation,idOfProject);
							projectConversationAdapter.notifyDataSetChanged();
						}  
					});
				}else if(projectConv != null){
					projectConversation.addAll(projectConv);
					//CacheHelper.saveMyProjectConversations(activity, projectConversation,idOfProject);
					saveTimeStampForProject(idOfProject, projectConv.get(0).getLast_post_time());
					projectConversationAdapter = new Conversation_ProjectConversation_Adapter(
							activity, projectConversation);
					activity.setListAdapter(projectConversationAdapter);
				}
			}
		});	
	}
	public void onPause(){
		super.onPause();
	}
	
	
	public void onStop(){
		super.onStop();
		
		//finish();
	}
	
	 private static void saveTimeStampForProject(String projectName, String lastPostTimeOfProject) {
			// null means to clear the old values
			SharedPreferences.Editor editor = mSettings.edit();
			if(lastPostTimeOfProject == null) {
				editor.remove(projectName);
			}
			else {
				Log.d(LOG_TAG, "Saving to SharedPreferences :" +lastPostTimeOfProject);
				editor.putString(projectName, lastPostTimeOfProject);
			}
			editor.commit();
		}
	
}
